package com.winner.data.util;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import cn.hutool.core.util.StrUtil;

/**
 * 输入表名, 执行main方法, 生成符合mybatis语法规范的 insertOne, updateOne Select条件查询 语句
 *
 * @author wangxinle5
 * @since 2022-11-11
 */
public class MyBatisGenerateInsertUpdateSelect {

    private static final String schemaPattern = null;

    private static final String TABLE_NAME = "user";

    private static final String URL = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT";

    private static final String USER_NAME = "root";

    private static final String PASSWORD = "123456";

    public static void main(String[] args) {
        try {
            // Step 1: Connect to the MySQL database
            Connection connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
            // Step 2: Query table names and field names
            DatabaseMetaData metaData = connection.getMetaData();
            String catalog = connection.getCatalog();
            // ResultSet tables = metaData.getTables(catalog, null, "%", null);
            // while (tables.next()) {
            // String tableName = tables.getString("TABLE_NAME");
            String tableName = TABLE_NAME;
            System.out.println("Table Name: " + tableName);

            ResultSet columns = metaData.getColumns(catalog, schemaPattern, tableName, null);
            StringBuilder insertStatement = new StringBuilder("INSERT INTO " + tableName + " (");
            StringBuilder updateStatement = new StringBuilder("UPDATE " + tableName + " SET ");
            StringBuilder selectStatement = new StringBuilder("SELECT ");
            StringBuilder deleteStatement = new StringBuilder("DELETE FROM ");
            StringBuilder selectWhere = new StringBuilder();
            int count = 0;
            ArrayList<String> filedList = new ArrayList<>();
            while (columns.next()) {
                String columnName = columns.getString("COLUMN_NAME");
                filedList.add(columnName);
                if (count > 0) {
                    insertStatement.append(", ");
                    updateStatement.append(", ");
                    selectWhere.append(" ");
                }
                insertStatement.append(columnName);
                // // update语句的值 转驼峰
                updateStatement.append(columnName).append(" = #{").append(convertToCamelCase(columnName)).append("}");
                selectWhere.append(" \n    <if test=\"").append(convertToCamelCase(columnName)).append(" != null and ")
                    .append(convertToCamelCase(columnName)).append(" != ''\">").append("\n        and ")
                    .append(columnName).append(" = #{").append(convertToCamelCase(columnName)).append("}")
                    .append("\n    </if>  ");
                count++;
                // <if test="module != null and module != ''"></if>
            }
            insertStatement.append(") VALUES (");
            for (int i = 0; i < count; i++) {
                if (i > 0) {
                    insertStatement.append(", ");
                }
                // java写一个工具类 , 将 user_id转为驼峰 userId的代码
                String camelCase = convertToCamelCase(filedList.get(i));
                insertStatement.append("#{").append(camelCase).append("}");
            }
            insertStatement.append(")");

            selectStatement.append(
                StrUtil.join(", ", filedList) + " from " + tableName + " \n<where> " + selectWhere + " \n</where>");

            deleteStatement.append(tableName
                + " where id in \n<foreach item=\"item\" collection=\"list\" separator=\",\" open=\"(\" close=\")\">\n"
                + "   #{item}\n" + "</foreach>");

            updateStatement.append("\nwhere id = #{id}");
            System.out.println("单表新增 :\n" + insertStatement);
            System.out.println("单表修改 :\n" + updateStatement);
            System.out.println("单表查询 :\n" + selectStatement);
            System.out.println("单表删除 :\n" + deleteStatement);
            // Step 3: Close the connection
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static String convertToCamelCase(String input) {
        StringBuilder result = new StringBuilder();

        // Split the input string by underscores
        String[] words = input.split("_");

        // Convert each word to camel case and append to the result
        for (int i = 0; i < words.length; i++) {
            String word = words[i].toLowerCase();
            if (i > 0) {
                // Capitalize the first character of each word (except the first word)
                word = capitalizeFirstCharacter(word);
            }
            result.append(word);
        }

        return result.toString();
    }

    private static String capitalizeFirstCharacter(String word) {
        return Character.toUpperCase(word.charAt(0)) + word.substring(1);
    }
}
